import type { ProcessBlock, BlockProcessor, PreBlock, PreCode, Row } from '../types';
import { isEmptyRow } from '../util';

const SPACE4 = '    ';

const isBlockBegin = (row: Row) => row.value.startsWith(SPACE4);

const deSpace4 = (row: Row): Row => ({ value: row.value.substring(4), type: 'row' });

const processBlock: ProcessBlock = (pbs) => {
  const result: PreBlock[] = [];
  let state = 0;
  for (const block of pbs) {
    const { type } = block;
    switch (state) {
      case 0: {
        if (type === 'row') {
          if (isBlockBegin(block)) {
            state = 1;
            result.push({ type: 'code', rows: [deSpace4(block)] });
          } else {
            result.push(block);
          }
        } else {
          result.push(block);
        }
        break;
      }
      case 1: {
        if (type === 'row') {
          if (isBlockBegin(block) || isEmptyRow(block)) {
            (result[result.length - 1] as PreCode).rows.push(deSpace4(block));
          } else {
            result.push(block);
            state = 0;
          }
        } else {
          result.push(block);
          state = 0;
        }
        break;
      }
    }
  }
  return result;
};

const codeBlockProcessor: BlockProcessor = {
  isBlockBegin,
  process: processBlock,
};

export default {
  processor: codeBlockProcessor,
};
